from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View
from haystack.views import SearchView

from goods.models import SKU, GoodsCategory


# Create your views here.


class ListView(View):

    def get(self, request, category_id):
        """
        获取商品列表页
        :param request: 请求对象
        :param category_id: 商品类别id
        :return:
        """
        '''获取请求参数'''
        page = request.GET.get("page")  # 当前页码
        page_size = request.GET.get("page_size")  # 每页数量
        ordering = request.GET.get("ordering")  # 排序方式

        '''从数据库获取商品数据'''
        # 根据商品类别id获取该类所有商品（SKU）
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by(ordering)

        '''对所有商品进行分页'''
        # 创建分页器对象，传入商品对象列表和每页数量，对商品进行分页
        paginator = Paginator(skus, page_size)
        # 获取当前页的商品：.page()传入一个数字获取指定页的商品
        page = paginator.page(page)

        '''提取当前页商品信息'''
        # 遍历每个商品，获取商品信息
        sku_list = []  # 创建一个列表存储商品信息
        for sku in page:
            sku_list.append({
                "id": sku.id,
                "default_image_url": sku.default_image_url,
                "name": sku.name,
                "price": sku.price
            })

        '''获取面包屑数据'''
        # 根据商品类别id获取该商品类型对象
        goodscategory = GoodsCategory.objects.get(id=category_id)
        # 根据该商品类型对象获取面包屑数据
        breadcrumb = goodscategory.get_breadcrumb()

        '''返回响应数据'''
        return JsonResponse({
            "code": 0,
            "errmsg": "OK",
            "breadcrumb": breadcrumb,
            "count": paginator.num_pages,
            "list": sku_list
        })


class HotGoodsView(View):

    def get(self, request, category_id):
        """
        获取热销商品排行数据
        :param request: 请求对象
        :param category_id: 热销类商品id
        :return: JSON
        """
        '''从数据库获取商品数据'''
        # 根据商品类别id获取所有热销商品（SKU），这里取排行前三的商品（.order_by('-sales')[:3]）
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:3]

        '''提取商品信息'''
        # 定义一个列表存储商品信息
        hot_sku_list = []
        # 遍历每个商品提取商品信息
        for sku in skus:
            hot_sku_list.append({
                "id": sku.id,
                "default_image_url": sku.default_image_url,
                "name": sku.name,
                "price": sku.price
            })

        '''返回响应数据'''
        return JsonResponse({
            "code": 0,
            "errmsg": "OK",
            "hot_skus": hot_sku_list
        })


class MySearchView(SearchView):
    """重写SearchView类"""
    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image_url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 拼接参数并返回
        return JsonResponse(data_list, safe=False)
